package com.example.pool.httpTest;

// 发异步http请求
// 线程池只有100个线程，1000个请求，每个线程需要用10次
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import com.alibaba.fastjson.JSON;
import com.example.pool.httpTest.util.CallbackTask;
import com.example.pool.httpTest.util.HttpAsyncClientUtil;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.slf4j.LoggerFactory;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;

public class TestAsyncHttpClient {

    static {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        List<ch.qos.logback.classic.Logger> loggerList = loggerContext.getLoggerList();
        loggerList.forEach(logger -> {
            logger.setLevel(Level.INFO);
        });
    }

    public static void main(String[] args) throws Exception {
        int threadCount = 1000;
        int corePoolSize = 5;
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, corePoolSize, 2, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(1000),new ThreadFactoryBuilder().setNameFormat("dw" + "-thread-%d").build(), new ThreadPoolExecutor.AbortPolicy());

        CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClientUtil.getHttpAsyncClient();
        CountDownLatch latch = new CountDownLatch(threadCount);
        httpAsyncClient.start();
        long startTime2 = System.currentTimeMillis();
        for (int i = 0; i < threadCount; i++) {
            CallbackTask callbackTask = new CallbackTask(latch, Integer.toString(i), System.currentTimeMillis());
            threadPoolExecutor.execute(new MyRunnable(httpAsyncClient, i, latch, callbackTask));
        }

        System.out.println("发送请求完成,耗时:"+ (System.currentTimeMillis() - startTime2));
        long startTime = System.currentTimeMillis();
        latch.await();
        long costTime = System.currentTimeMillis() - startTime;
        System.out.println("总共耗时："+ costTime);
        httpAsyncClient.close();
        threadPoolExecutor.shutdown();

    }

    private static class MyRunnable implements Runnable {
        private CloseableHttpAsyncClient httpclient;
        private int i;
        private CountDownLatch latch;
        private CallbackTask callbackTask;
        public MyRunnable(CloseableHttpAsyncClient httpclient, int i, CountDownLatch latch, CallbackTask callbackTask) {
            this.httpclient = httpclient;
            this.i = i;
            this.latch = latch;
            this.callbackTask = callbackTask;
        }

        @Override
        public void run() {
            try {
                final HttpGet request = new HttpGet("http://localhost:8080/get");
//                System.out.println("发送请求" + i);
                httpclient.execute(request, callbackTask);
//                System.out.println("发送请求" + i + "完成");
                System.out.println("threadPool:"+Thread.currentThread().getName()+"处理的连接："+i);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
